package com.ccx.coachsite.weibo.auth2.net;


import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.util.HashMap;

import android.content.Context;
import android.net.Uri;
import android.text.TextUtils;

import com.ccx.coachsite.weibo.auth2.WeiBoContants;
import com.ccx.coachsite.weibo.auth2.vo.LoginUser;
import com.ccx.coachsite.weibo.auth2.vo.User;
import com.ccx.coachsite.weibo.json.JSONObject;


public class Weibo {
	
	private static Weibo mInstance;
	private Context mContext;
	private Weibo(Context context)
	{
		mContext=context;
	}
	
	public static Weibo getInstance(Context context)
	{
		if(mInstance==null)
			mInstance=new Weibo(context);
		return mInstance;
	}
	
	/**
	 * 登陆微博
	 * @param userName 帐号
	 * @param password 密码
	 * @return
	 * @throws Exception
	 */
	public LoginUser doLogin(String userName,String password) throws Exception
	{
		String url=WeiBoContants.Auth.WEIBO_AUTH_URL;
		HashMap<String, String> paramMap=new HashMap<String, String>();
		paramMap.put("client_id", WeiBoContants.App.CONSUMER_KEY_PANDA_HOME);
		paramMap.put("client_secret", WeiBoContants.App.CONSUMER_SECRET_PANDA_HOME);
		paramMap.put("grant_type", "password");
		paramMap.put("username", userName);
		paramMap.put("password", password);
		
		Response response=HttpUtil.openUrl(mContext, url, "POST", paramMap, null, null);
		JSONObject jObj=response.asJSONObject();
		Token token=new Token(jObj);
		LoginUser loginUser=new LoginUser();
		loginUser.setAccessToke(token.getAccessToken());
		loginUser.setAccount(userName);
		loginUser.setLoginTime(System.currentTimeMillis());
		loginUser.setPackageName(WeiBoContants.App.PANDA_HOME_PACKAGE);
		loginUser.setUid(token.getUid());
		wrapDetailToLoginUser(loginUser);
		return loginUser;
	}
	
	/**
	 * 获取登陆用户的详细信息
	 */
	public void wrapDetailToLoginUser(LoginUser loginUser) throws Exception
	{
		User user=getUser(loginUser.getUid(),null,loginUser.getAccessToke());
		loginUser.setUserDetailInfo(user);
	}
	
	
	/**
	 * 获取用户信息
	 * @param uid
	 * @param accessToken
	 * @return
	 * @throws Exception
	 */
	public User getUser(String uid,String screenName,String accessToken) throws Exception
	{
		
		String url=WeiBoContants.WeiBo.GET_USER_URL;
		HashMap<String, String> paramMap=new HashMap<String, String>();
		if(!TextUtils.isEmpty(uid))
			paramMap.put("uid", uid);
		else
			paramMap.put("screen_name", screenName);
		Response response=HttpUtil.openUrl(mContext, url, "GET", paramMap, null, accessToken);
		JSONObject jObj=response.asJSONObject();
		User user=new User(jObj);
		return user;
	}
	
	/**
	 * 上传图片并发布一条新微博 
	 * @param content
	 * @param uri
	 * @return
	 * @throws Exception
	 */
	public boolean uploadStatus(String content, Uri uri,String accessToken) throws Exception
	{
		String url=WeiBoContants.WeiBo.SEND_WEIBO_URL;
		HashMap<String, String> paramMap=new HashMap<String, String>();
		paramMap.put("status", content);
		
		ByteArrayOutputStream bos=null;
 		BufferedInputStream bis=null;
 		try {
 	    	//读取发送文件的字节
 			bos=new ByteArrayOutputStream();
 			if ( uri!=null ){
	 			if(uri.toString().indexOf("content://")>-1)
	 				bis=new BufferedInputStream(mContext.getContentResolver().openInputStream(uri));
	 			else{
	 				String filePath=uri.toString().substring(uri.toString().indexOf("sdcard"));
	 				bis=new BufferedInputStream(new FileInputStream(filePath));
	 			}
 			}
 			/*byte[] tmpBytes=new byte[1024*4];
 			int len=-1;
 			while((len=bis.read(tmpBytes))!=-1)
 			{
 				bos.write(tmpBytes, 0, len);
 				bos.flush();
 			}*/
 			//开始发布
 			HttpUtil.openUrl(mContext, url, "POST", paramMap, bis, accessToken);
		} catch (Exception e) {
			throw e;
		} finally{
    		try {
				if(bis!=null)
					bis.close();
				if(bos!=null)
					bos.close();
			} catch (Exception e) {
			}
    	}
		return true;
	}
	
	/**
	 * 关注用户
	 */
	public boolean addFriend(String uid,String screenName,String accessToken) throws Exception
	{
		String url=WeiBoContants.WeiBo.ADD_FIRENDS_URL;
		HashMap<String, String> paramMap=new HashMap<String, String>();
		if(uid!=null)
			paramMap.put("uid",uid);
		else
			paramMap.put("screen_name",screenName);
		HttpUtil.openUrl(mContext, url, "POST", paramMap, null, accessToken);
		return true;
	}
	
	
	/**
	 * 微博登录帐号表
	 */
	public static class LoginTable{
		
		public final static String TABLE_NAME="webologin";
		
		public static final String ID="_id";
		
		/**微博用户ID*/
		public static final String USER_ID="user_id";
		/**昵称*/
		public static final String SCREEN_NAME="screen_name"; 
		/**微博授权密钥*/
		public static final String ACCESS_TOKEN="access_token";
		/**登陆帐号*/
		public static final String ACCOUNT="account";
		
		/**登陆的桌面包名，区别是从哪个桌面登陆微博*/
		public static final String PACKAGE_NAME="package";
		
		/**登陆时间*/
		public static final String LOGIN_TIME="time";
		
		public static final String CREATE_TABLE="create table if not exists "
																+TABLE_NAME
																+"("
																+ID+" integer primary key,"
																+USER_ID+" text,"
																+SCREEN_NAME+" text,"
																+ACCESS_TOKEN+" text,"
																+ACCOUNT+" text,"
																+PACKAGE_NAME+" text,"
																+LOGIN_TIME+" integer"
																+")";
	}//end class LoginTable
	
}




































